package com.springboot.multiplethread.config;

import com.springboot.multiplethread.properties.ThreadPoolProperties;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author sam
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Resource
    private ThreadPoolProperties threadPoolProperties;

    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
        // 最大线程数
        executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
        // 任务队列容量（阻塞队列）
        executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
        // 空闲线程存活时间
        executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveTime());
        // 线程名前缀
        executor.setThreadNamePrefix(threadPoolProperties.getThreadNamePrefix());
        // 线程工厂
//        executor.setThreadFactory();
        // 允许核心线程超时
//        executor.setAllowCoreThreadTimeOut(true);

        // 线程池拒绝策略 -> 由调用线程处理该任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
